package com.realphim.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.realphim.app.adapter.AdapterGridCategory;
import com.realphim.app.model.ModelCategory;
import com.realphim.app.model.ModelPhim;
import com.realphim.app.util.CommonDefine;
import com.realphim.app.util.JSONParser;

public class ActivityCategory extends Activity implements CommonDefine,
        IXListViewListener {

    private final String TAG = "ActivityCategory";

    private Context _context;

    private ImageView ivBack;

    private TextView tvCategoryName;

    private XListView gvPhim;

    private ProgressBar pbLoad;

    private String categoryName;

    private String urlGetPhim;

    private List<ModelPhim> listPhimCate = new ArrayList<ModelPhim>();

    private AdapterGridCategory adapterCate;

    private int posCover = 0;

    private int start = 0;

    private int item_per_page;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        _context = this;
        Bundle mBundle = getIntent().getExtras();
        if (mBundle != null) {
            categoryName = mBundle.getString(KeyBundle.CATEGORY_NAME);
            urlGetPhim = mBundle.getString(KeyBundle.URL_GET_PHIM);
        }

        item_per_page = getResources().getInteger(R.integer.item_per_page);

        initView();
    }

    private void initView() {
        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvCategoryName = (TextView) findViewById(R.id.tvCategoryName);
        gvPhim = (XListView) findViewById(R.id.gvPhim);
        gvPhim.setPullRefreshEnable(false);
        gvPhim.setPullLoadEnable(false);
        gvPhim.setXListViewListener(this);
        adapterCate = new AdapterGridCategory(_context, listPhimCate);
        gvPhim.setAdapter(adapterCate);
        pbLoad = (ProgressBar) findViewById(R.id.pbLoadCate);

        ivBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });

        tvCategoryName.setText(categoryName);

        new AsyncTaskGetListCate()
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private void finishActivity() {
        finish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    private class AsyncTaskGetListCate extends
            AsyncTask<Integer, Integer, Boolean> {

        private List<ModelPhim> listTemp = new ArrayList<ModelPhim>();

        @Override
        protected Boolean doInBackground(Integer... params) {
            boolean result = false;
            try {

                String strUrl = urlGetPhim + "&" + ServiceParam.LIMIT + "="
                        + item_per_page + "&" + ServiceParam.START + "="
                        + start;
                Log.v(TAG, strUrl);
                String jsonResult = new JSONParser().getJSONFromUrl(strUrl,
                        METHOD_GET, null);
                Log.i(TAG, jsonResult);
                JSONArray arrResult = new JSONObject(jsonResult)
                        .getJSONArray("data");

                for (int i = 0; i < arrResult.length(); i++) {
                    JSONObject objPhim = arrResult.getJSONObject(i);
                    ModelPhim myPhim = new ModelPhim();
                    myPhim.id = objPhim.getInt(KeyPhim.id);
                    myPhim.title = objPhim.getString(KeyPhim.title);
                    myPhim.titleTranslate = objPhim
                            .getString(KeyPhim.title_translate);
                    myPhim.imageUrl = objPhim.getString(KeyPhim.image);
                    myPhim.thumbnailUrl = objPhim.getString(KeyPhim.thumbnail);
                    myPhim.description = objPhim.getString(KeyPhim.description);
                    myPhim.lastEp = objPhim.getInt(KeyPhim.last_episode);
                    myPhim.maxEp = objPhim.getInt(KeyPhim.max_episode);
                    myPhim.isHD = objPhim.getInt(KeyPhim.is_hd);
                    myPhim.imb = objPhim.getString(KeyPhim.imdb);
                    myPhim.publishYear = objPhim
                            .getString(KeyPhim.publish_year);
                    myPhim.duration = objPhim.getInt(KeyPhim.duration);
                    myPhim.isFeature = objPhim.getInt(KeyPhim.is_featured);
                    myPhim.isCinema = objPhim.getInt(KeyPhim.is_cinema);
                    myPhim.rate = objPhim.getString(KeyPhim.rate);
                    myPhim.director = objPhim.getString(KeyPhim.director);
                    myPhim.viewFake = objPhim.getString(KeyPhim.view_fake);
                    myPhim.label = objPhim.getString(KeyPhim.label);
                    myPhim.actors = objPhim.getString(KeyPhim.actors);
                    myPhim.nation = objPhim.getString(KeyPhim.nation);
                    myPhim.tag = objPhim.getString(KeyPhim.tags);
                    myPhim.uploadBy = objPhim.getString(KeyPhim.upload_by);
                    myPhim.creatDate = objPhim.getString(KeyPhim.created_date);
                    myPhim.viewCount = objPhim.getString(KeyPhim.view_count);
                    myPhim.viewCountMonth = objPhim
                            .getString(KeyPhim.view_count_month);
                    myPhim.viewCountWeek = objPhim
                            .getString(KeyPhim.view_count_week);

                    JSONArray arrCategory = objPhim
                            .getJSONArray(KeyPhim.category);
                    for (int j = 0; j < arrCategory.length(); j++) {
                        JSONObject objCate = arrCategory.getJSONObject(j);
                        ModelCategory myCate = new ModelCategory();
                        myCate.id = objCate.getInt(KeyCategory.id);
                        myCate.title = objCate.getString(KeyCategory.title);
                        myPhim.listCategories.add(myCate);
                    }

                    listTemp.add(myPhim);

                    result = true;

                }
            } catch (Exception e) {
                Log.e(TAG, e.toString() + "");
                result = false;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            gvPhim.stopLoadMore();
            if (result) {
                pbLoad.setVisibility(View.GONE);
                start += listTemp.size();
                for (int i = 0; i < listTemp.size(); i++) {
                    listPhimCate.add(listTemp.get(i));
                }
                adapterCate.notifyDataSetChanged();
                Log.d("LIST PHIM SIZE", "" + adapterCate.getCount());
                if (listPhimCate.size() > 0) {
                    new AsyntaskLoadCover()
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } else {
                    Toast.makeText(_context, "Không tìm thấy phim",
                            Toast.LENGTH_SHORT).show();
                }
                if (listTemp.size() < item_per_page) {
                    gvPhim.setPullLoadEnable(false);
                } else {
                    gvPhim.setPullLoadEnable(true);
                }

            } else {
                showDialogNoConnection();
            }
        }

    }

    private class AsyntaskLoadCover extends AsyncTask<String, String, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO Auto-generated method stub
            InputStream iStream = null;
            URL url;
            String name;
            try {

                url = new URL(listPhimCate.get(posCover).thumbnailUrl);
                name = listPhimCate.get(posCover).title;

                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
                        + name + ".png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                Bitmap b = BitmapFactory.decodeStream(iStream);
                b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);

                Bitmap result = Bitmap.createScaledBitmap(b, 200, 300, true);
                fOutStream.flush();
                fOutStream.close();
                b.recycle();
                return result;

            } catch (Exception e) {
                Log.e("LoadImage", e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            listPhimCate.get(posCover).thumbnailBitmap = result;
            adapterCate.notifyDataSetChanged();
            if (posCover < listPhimCate.size() - 1) {
                posCover++;
                new AsyntaskLoadCover()
                        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        }
    }

    private void showDialogNoConnection() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(_context);
        dialog.setTitle("Connection");
        dialog.setMessage("Can not connect to server");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLoadMore() {
        new AsyncTaskGetListCate()
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
